package org.example.system.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.GifCaptcha;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
import org.example.system.entity.Employee;
import org.example.system.service.AuthService;
import org.example.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * 认证控制器
 */
@RestController
@RequestMapping("/admin")
@Slf4j
public class AuthController {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private AuthService authService;
    /**
     * 响应验证码图片
     */
    @GetMapping("/validcode")
    public void validCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        GifCaptcha lineCaptcha = CaptchaUtil.createGifCaptcha(220, 100,4);
        String code = lineCaptcha.getCode();//获得生成的验证码
        log.info("--------AuthController | validCode | code:{}",code);
        String clientUid = request.getParameter("clientUid");//客户端id
        log.info("--------AuthController | validCode | clientUid:{}",clientUid);
        //存储到redis缓存
        String key = "LOGIN_VALID_CODE:" + clientUid;
        redisTemplate.opsForValue().set(key,code,5, TimeUnit.MINUTES);//验证码5分钟有效
        //输出图片给浏览器
        lineCaptcha.write(response.getOutputStream());
        response.getOutputStream().flush();//把缓存中的图片数据刷新出去
    }

    /**
     * 系统用户登录
     * @param loginEmployee
     * @return
     */
    @PostMapping("/login")
    public R login(@RequestBody Employee loginEmployee){
        log.info("--------AuthController | login | input:{}", JSON.toJSONString(loginEmployee));
        if (StrUtil.isEmpty(loginEmployee.getUsername()) ||
        StrUtil.isEmpty(loginEmployee.getPassword()) ||
        StrUtil.isEmpty(loginEmployee.getValidCode()) ||
        StrUtil.isEmpty(loginEmployee.getClientUid())){
            return R.fail("参数错误");
        }

        //判断验证码是否正确
        String key = "LOGIN_VALID_CODE:" + loginEmployee.getClientUid();
        String code = (String)redisTemplate.opsForValue().get(key);
        if (!loginEmployee.getValidCode().equals(code)){
            return R.fail("验证码错误");
        }
        Object token = authService.login(loginEmployee);
        return R.ok(token);
    }
}
